<template>
  <div>
    <!-- <el-card id="table-head-block">
      <b>项目数据</b>
    </el-card> -->
    <!-- <p>{{chosenDate}}</p> -->
    <el-card id="table-block">
      <div class="block">
        <el-row>
          <el-col :span="8">
            <el-select v-model="projectItem"
                       filterable
                       @change="sendRequest"
                       placeholder="请选择项目">
              <el-option v-for="(item,index) in options4activities"
                         :key="index"
                         :label="item.label"
                         :value="item.label">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="depItem"
                       filterable
                       @change="sendRequest"
                       placeholder="搜索部门">
              <el-option v-for="(item,index) in options4depart"
                         :key="index"
                         :label="item.label"
                         :value="item.label">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="checkOpt"
                       placeholder="查询日期类型">
              <el-option v-for="item in options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <br />
        <el-row>
          <span class="demonstration">选择日期</span>
          <el-date-picker v-if='checkOpt == "false"'
                          v-model="chosenDate"
                          type="daterange"
                          align="right"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          @change="sendRequest"
                          :picker-options="pickerOptions4Week">
          </el-date-picker>
          <el-date-picker v-else
                          v-model="chosenDate"
                          type="monthrange"
                          align="right"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始月份"
                          end-placeholder="结束月份"
                          value-format="yyyy-MM"
                          @change="sendRequest"
                          :picker-options="pickerOptions4Month">
          </el-date-picker>
        </el-row>
        <br />
        <el-row>
          <el-col :span="12">
            <wt-button type="primary"
                       plain
                       round
                       @click="exportExcel">点击导出<i class="el-icon-download el-icon--right"></i></wt-button>
          </el-col>
          <el-col :span="12">
            <wt-button type="primary"
                       plain
                       round
                       @click="showCharts = true">数据分析<i class="el-icon-s-data el-icon--right"></i></wt-button>
          </el-col>
        </el-row>
      </div>
      <el-table id="table"
                :data="tableData"
                style="width: 100%">
        <el-table-column prop="name"
                         label="姓名"
                         fixed
                         width="150"
                         align="center">
        </el-table-column>
        <el-table-column prop="area"
                         label="区域"
                         fixed
                         width="150"
                         align="center">
        </el-table-column>
        <el-table-column v-if='checkOpt == "true"'
                         align="center">
          <el-table-column v-for="(item, index) in colLabel"
                           :key="index"
                           :label="item">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.effort[index] }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column v-else
                         align="center">
          <el-table-column v-for="(item, index) in colLabel"
                           :key="index"
                           :label="item">
            <template slot-scope="scope">
              <span v-if="scope.row.effort"
                    style="margin-left: 10px">{{ scope.row.effort[index] }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
    <charts v-if="showCharts"
            :tableData="statisticsData"
            :flag="flag"
            @closedialog="showCharts = false" />
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import charts from "@/components/charts";
import WtButton from "@/components/Button";
import dateInfo from "../utils/dateInfo";
export default {
  components: {
    charts,
    WtButton
  },
  data() {
    return {
      flag: 2,
      showCharts: false,
      options: [
        {
          value: "true",
          label: "按月查询"
        },
        {
          value: "false",
          label: "按周查询"
        }
      ],
      checkOpt: "false", //false 按月, true 按周
      today: "",
      chosenDate: "",
      colLabel: [],
      colNum: "",
      tableData: [
        {
          name: "",
          area:"",
          effort: []
        }
      ],
      statisticsData: [
        {
          name: "",
          area:"",
          effort: []
        }
      ],
      pickerOptions4Week: {
        firstDayOfWeek: 1,
        shortcuts: [
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      pickerOptions4Month: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            }
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      options4activities: [
        // {
        //   label: ""
        // }
      ],
      options4depart: [
        // {
        //   label: ""
        // }
      ],
      projectItem: "",
      depItem: ""
    };
  },
  methods: {
    // *发送查询请求
    sendRequest() {
      this.flushDate();
      if (
        this.projectItem &&
        this.checkOpt &&
        this.chosenDate[0] &&
        this.chosenDate[1] &&
        this.depItem
      ) {
        this.$api.userInfo
          .requestProjectData({
            projectName: this.projectItem,
            isMonth: this.checkOpt,
            startTime: this.chosenDate[0],
            endTime: this.chosenDate[1],
            department: this.depItem
          })
          .then(response => {
            this.tableData = [];
            this.statisticsData = [];
            // console.log("接收到的数据", response.data)
            if (response.data.names) {
              let effortSum = [];
              for (let j = 0; j < response.data.efforts[0].length; j++) {
                effortSum[j] = 0;
              }
              //工时数据推入
              for (var i = 0; i < response.data.names.length; i++) {
                this.tableData.push({
                  name: response.data.names[i],
                  area: response.data.area[i],
                  effort: response.data.efforts[i]
                });
                this.statisticsData.push({
                  name: response.data.names[i],
                  area: response.data.area[i],
                  effort: response.data.efforts[i]
                });
                // 按列求和
                if (response.data.efforts[0].length) {
                  for (let j = 0; j < response.data.efforts[0].length; j++) {
                    effortSum[j] += response.data.efforts[i][j];
                  }
                }
              }
              this.tableData.push({
                name: "Summary",
                area: "-",
                effort: effortSum
              });
            } else {
              console.log("数据为空");
            }
          })
          .catch(error => {
            console.log("error: ", error);
          });
      }
    },
    // *刷新表头时间
    flushDate() {
      var temp = [];
      if (!this.chosenDate[0] || !this.chosenDate[1]) {
        return;
      }
      if (this.checkOpt == "false") {
        //周的时间列表处理
        // console.log("按月处理,不需要处理后的时间", this.chosenDate);
        let yearDiff =
          parseInt(this.chosenDate[1].split("-")[0]) -
          parseInt(this.chosenDate[0].split("-")[0]);
        var begin = parseInt(dateInfo.getWeekNum(this.chosenDate[0]));
        var end = parseInt(dateInfo.getWeekNum(this.chosenDate[1]));
        if (yearDiff >= 1) {
          var t = 0;
          for (i = 0; i <= yearDiff; i++) {
            // Math.floor(parseInt(this.NumDates((new Date(this.chosenDate[1])).getFullYear() + i))/7);
            let weekNum = dateInfo.getweekNums(
              new Date(this.chosenDate[0]).getFullYear() + i
            );
            if (i == 0) {
              for (var j = begin; j <= weekNum; j++) {
                temp[t++] =
                  "第" + (j % weekNum == 0 ? weekNum : j % weekNum) + "周";
              }
            } else if (i == yearDiff) {
              for (var j = 1; j <= end; j++) {
                temp[t++] =
                  "第" + (j % weekNum == 0 ? weekNum : j % weekNum) + "周";
              }
            } else {
              for (var j = 1; j <= weekNum; j++) {
                temp[t++] = "第" + j + "周";
              }
            }
          }
        } else {
          let weekNum = dateInfo.getweekNums(
            new Date(this.chosenDate[0]).getFullYear()
          );
          this.colNum = end - begin + 1;
          for (var j = 0; j < this.colNum; j++) {
            temp[j] =
              "第" +
              (parseInt(begin % weekNum) == 0 ? weekNum : begin % weekNum) +
              "周";
            begin++;
          }
        }
      } else {
        // 月的时间列表处理
        this.chosenDate[0] = this.chosenDate[0] + "-" + "01";
        this.chosenDate[1] =
          this.chosenDate[1] +
          "-" +
          dateInfo.getMonthDaysNum(
            this.chosenDate[1].split("-")[0],
            this.chosenDate[1].split("-")[1]
          );
        // console.log("按月处理,处理后的时间", this.chosenDate);
        if (
          this.chosenDate[0].split("-")[0] == this.chosenDate[1].split("-")[0]
        ) {
          var begin = parseInt(this.chosenDate[0].split("-")[1]);
          var end = parseInt(this.chosenDate[1].split("-")[1]);
          this.colNum = end - begin + 1;
          for (var i = begin; i <= end; i++) {
            temp[i - begin] = i + "月";
          }
        } else {
          // 如果年数不同
          var begin = parseInt(this.chosenDate[0].split("-")[1]);
          var end =
            12 *
              parseInt(
                this.chosenDate[1].split("-")[0] -
                  this.chosenDate[0].split("-")[0]
              ) +
            parseInt(this.chosenDate[1].split("-")[1]);
          // console.log(begin, end);
          this.colNum = end - begin + 1;
          var k = 0;
          for (var i = begin; i <= end; i++) {
            if (i <= 12) {
              temp[i - begin] = i + "月";
            } else {
              temp[i - begin] = i - 12 * parseInt(k / 12 + 1) + "月";
              ++k;
            }
          }
        }
      }
      this.colLabel = temp;
    },
    // *定义导出Excel表格事件
    exportExcel: function() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#table"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "项目数据.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    }
  },
  mounted: function() {
    this.$api.userInfo
      .requestActivites()
      .then(response => {
        for (var i = 0; i < response.data.projectsName.length; i++) {
          this.options4activities.push({
            label: response.data.projectsName[i]
          });
        }
        // console.log("项目: ", this.options4activities);
      })
      .catch(error => {
        console.log("error: ", error);
      });
    this.$api.userInfo
      .requestDepartments()
      .then(response => {
        for (var i = 0; i <= response.data.departments.length; i++) {
          if (i == 0) {
            this.options4depart.push({ label: "全部" });
          } else {
            this.options4depart.push({
              label: response.data.departments[i - 1]
            });
          }
        }
        // console.log("部门", this.options4depart);
      })
      .catch(error => {
        console.log("error: ", error);
      });
  }
  // created: function() {},
  // computed: function() {}
};
</script>


<style lang="less" scoped>
.block {
  margin-bottom: 30px;
  margin-top: 25px;
}
#table-block {
  width: 85%;
  margin: 50px auto;
  border-radius: 25px;
  padding: 0px 10px;
}
#table-head-block {
  width: 200px;
  font-size: 20px;
  margin: 20px auto;
  border-radius: 25px;
}
</style>
